package com.sc.weixin.order;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sc.dal.common.pagination.Page;
import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.dto.order.OrderDetailDto;
import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.dto.promotion.PromotionGoodsSkuDto;
import com.sc.dal.mapper.order.OrderMapper;
import com.sc.dal.model.cart.Cart;
import com.sc.dal.model.consultComment.ConsultComment;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsStock;
import com.sc.dal.model.member.Member;
import com.sc.dal.model.member.MemberAddress;
import com.sc.dal.model.member.MemberNews;
import com.sc.dal.model.order.Express;
import com.sc.dal.model.order.Order;
import com.sc.dal.model.order.OrderBalance;
import com.sc.dal.model.order.OrderDetail;
import com.sc.dal.model.order.OrderPayment;
import com.sc.dal.model.order.OrderShip;
import com.sc.dal.model.order.Orders;
import com.sc.dal.model.order.Products;
import com.sc.dal.model.order.Shop;
import com.sc.dal.model.order.Tax;
import com.sc.dal.model.promotion.PromotionOrderRecord;
import com.sc.dal.model.seller.Seller;
import com.sc.service.cart.CartService;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.goods.GoodsService;
import com.sc.service.goods.GoodsSkuService;
import com.sc.service.member.MemberAddressService;
import com.sc.service.member.MemberCardService;
import com.sc.service.member.MemberService;
import com.sc.service.order.OrderService;
import com.sc.service.promotion.PromotionService;
import com.sc.weixin.BaseController;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Arith;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.DateUtil;
import com.sc.util.data.MakeOrderNum;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
/**
 * @ClassName: AppCartController
 * @Description: 购物车管理
 * @author LeiJia
 * @date 2017年04月28日 下午1:59:26
 * @version V1.0
 */
@Controller
@RequestMapping("/order")
public class OrderController  extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());	
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private MemberAddressService   memberAddressService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private GoodsSkuService goodsSkuService;
	
	@Autowired
	private PromotionService  promotionService;
	
	@Autowired
	private MemberCardService memberCardService;
	
	@Autowired
	private ConsultCommentService  consultCommentService;
	
	//确认支付银行正在处理
	@RequestMapping(value="loading")
	public String loading(){
		return "/order/loading";
	}
	
	//待评价
	@RequestMapping(value="to_evaluate")
	public String to_evaluate(){
    	return "/order/to_evaluate";
    }
	//评论成功
	@RequestMapping(value="comment_success")
	public String comment_success(){
		return "/order/comment_success";
	}
	
	
	//评论
	@RequestMapping(value="evaluate")
	public String evaluate(Model model,String orderId,String goodsId){
		List<Products> products = orderService.selectOrderProductsByOrderId(orderId,goodsId);
		for(Products product : products){
			if(Common.isNotEmpty(product.getPicture()))				
			     product.setPicture(ConfigBeanAdapter.fileAccessAddress + product.getPicture());
		}
		Order order = orderService.selectByPrimaryKey(orderId);
		Seller seller = orderService.getSellerById(Integer.valueOf(order.getSellerId()));//店铺信息
		model.addAttribute("products", products);
		model.addAttribute("shopName",seller.getSellerName());
		model.addAttribute("orderId",order.getOrderId());
		return "/order/evaluate";
	}
	//获取商品的评论列表
	public List<Products> getProducts(List<Products>  products,String orderId){
		for(Products product :products){
			List<ConsultComment> commentList =new ArrayList<ConsultComment>();
			ConsultComment comment = new ConsultComment();
			comment.setOrderId(orderId);
			comment.setGoodsId(product.getProductId());
			commentList = consultCommentService.selectCommentByParam(comment);
			for(ConsultComment c : commentList){
				if(Common.isNotEmpty(c.getFilePicture()))
			     	c.setFilePicture(ConfigBeanAdapter.fileAccessAddress + c.getFilePicture());
				if(Common.isNotEmpty(c.getFilePicture2()))
					c.setFilePicture2(ConfigBeanAdapter.fileAccessAddress + c.getFilePicture2());
				if(Common.isNotEmpty(c.getFilePicture3()))
					c.setFilePicture3(ConfigBeanAdapter.fileAccessAddress + c.getFilePicture3());
			}
			product.setCommentList(commentList);
		}
		return products;
	}
	//追加评论
	@RequestMapping(value="/addEvaluate")
	public String addEvaluate(Model model ,String orderId,String goodsId){
		List<Products> products = orderService.selectOrderProductsByOrderId(orderId,goodsId);
		for(Products product : products){
			if(Common.isNotEmpty(product.getPicture()))				
			     product.setPicture(ConfigBeanAdapter.fileAccessAddress + product.getPicture());
		}
		Order order = orderService.selectByPrimaryKey(orderId);
		Seller seller = orderService.getSellerById(Integer.valueOf(order.getSellerId()));//店铺信息

		//查询商品的评论列表
		products=getProducts(products,orderId);
		model.addAttribute("products", products);
		model.addAttribute("shopName", seller.getSellerName());
		model.addAttribute("orderId",order.getOrderId());
		return "/order/addEvaluate";
	}
	//订单详情页面
	@RequestMapping(value="/orderData")
	public String order_details(){
		return "/order/orderData";
	}
	//商品立即购买页面
	@RequestMapping(value="/order")
	public ModelAndView product_confirm_order(HttpServletRequest request,HttpServletResponse response){		
		ModelAndView mav = new ModelAndView("/order/order");
		//获取收货地址ID
		String maId = request.getParameter("maId");
		MemberAddress mAddress = null;
		if(Common.isNotEmpty(maId)){
			mAddress = memberAddressService.selectAddressById(maId);
			mav.addObject("mAddress", mAddress);
			mav.addObject("ma_id", maId);
		}else{
			mav.addObject("ma_id", null);
		}
		return mav;
	}

	/**
	 * @Title: goBuy
	 * @Description 商品立即购买(与购物车结算功能类似：检查商品数量与库存；获取商品促销类别,计算各种优惠对应的商品总额)
	 * @date 2017年5月11日上午11:17
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value = "goBuy",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> goBuy(Model model,HttpServletRequest request,HttpServletResponse response,Integer goodsId ,String goods_sku_id,Integer mount){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			List<Shop> shops = new ArrayList<Shop>();
			Shop shop = new Shop();
			if( goodsId == null || mount == null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				resultMap.put("sessionValid", true); //会话失效
    			return resultMap;
			}
			Goods goods = goodsService.selectByPrimaryKey(goodsId);
			
			//判断商品数量与库存
			if(Common.isNotEmpty(goods.getPicture()))
				goods.setPicture(ConfigBeanAdapter.fileAccessAddress + goods.getPicture()); 
			int stocknum = getProductStockNum(goodsId,goods_sku_id);
			
			if(stocknum <= 0 || stocknum < mount){
				resultMap.put("stockShortMessge" , goods.getName() + "商品库存不足"+"请修改购物车商品数量");
			}
			//获取商品的促销类型与各种类型下的订单总额
            //************************************单个商品促销活动***************************************************************
			List<Map<String,Object>> goodsProMapList = new ArrayList<Map<String, Object>>();
			//商品促销活动
			Products product =  getProducts( goods_sku_id, goods,  member, mount, stocknum ) ;
			//判断部分商品活动集合中是否已有该商品参与促销了
			if(isGoodsIdNotExistInGoodsProMapList(goodsProMapList,product.getProductId())){
				//查询商品参与的促销活动
				List<PromotionGoodsSkuDto>  goodsProList = promotionService.getGoodsProInfo(product.getProductId());
				if(goodsProList != null && goodsProList.size() > 0){
					for(PromotionGoodsSkuDto goodsSkuDto : goodsProList){						
						List<PromotionDetailDto> goodsProDetailList = promotionService.selectProDetailByProId(goodsSkuDto.getPro_id());
						for(PromotionDetailDto proDetailDto :goodsProDetailList){
                            Date now_time = new Date(); //现在时间
						    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
						    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
						    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
								Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
								//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
								proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
								proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
								proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
								String pro_type = proDetailDto.getPro_type();
								String pro_money = proDetailDto.getPro_money();
								String pro_count = proDetailDto.getPro_count();
								String pro_rate = proDetailDto.getPro_rate();								

								String pro_gooods = proDetailDto.getPro_goods();
								proDetailMap.put("productId", product.getProductId());
								proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
								proDetailMap.put("proType", pro_type);//促销类型
								proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
								if(goodsWhetherMeetWholeActivity(pro_type,proDetailMap,product)){
									goodsProMapList.add(proDetailMap);
								}
						    }
						}
					}
				}
			}
			product.setGoodsProMapList(goodsProMapList);
            //************************************单个商品促销活动***************************************************************

            //************************************店铺促销活动开始*********************************************************************

		    BigDecimal totalAmount = null;//数据封装

		    if(product.getDiscountMarketPrice() != null){
		    	totalAmount = new BigDecimal(mount).multiply(product.getDiscountMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		    }else{
		    	totalAmount = new BigDecimal(mount).multiply(product.getMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		    }
		    shop.setTotalAmount(totalAmount);
		    shop.setItemnum(mount);
		//	shop.setItemnum(mount);
			shop.setSellerId(Constants.SELLERID);
			shop.setShopName(Constants.SHOPNAME);
		    //计算订单的促销方案
			List<Map<String,Object>> wholeOrderPro = new ArrayList<Map<String, Object>>();
			//查询所有促销活动
			List<Map<String,Object>> proDetailDtoMapList  =  promotionService.selectByParam(null);
			if(proDetailDtoMapList != null && proDetailDtoMapList.size() >0){
				for(Map<String,Object> map :proDetailDtoMapList){
                    Date now_time = new Date(); //现在时间
				    Date pro_start = DateUtil.dateStrToYMDHMSDate(map.get("pro_start").toString()); //促销开始时间
				    Date pro_end  = DateUtil.dateStrToYMDHMSDate(map.get("pro_end").toString()); //促销结束时间

				    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
						Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
						String pro_type ="";
						if(map.get("pro_type") != null)
					       pro_type = map.get("pro_type").toString();
						proDetailMap.put("proType", pro_type);
						String pro_money ="";
						if(map.get("pro_money") != null)
						   pro_money = map.get("pro_money").toString();
						String pro_count = "";
						if(map.get("pro_count") != null)
						   pro_count = map.get("pro_count").toString();
						String pro_rate = "";
						if(map.get("pro_rate") != null)
						   pro_rate =map.get("pro_rate").toString();
						//String pro_title="";
						//if(map.get("pro_title") != null)
						//	pro_title =  map.get("pro_title").toString();
						//proDetailMap.put("proTitle", pro_title);//促销名称
						String pro_detail_id="";
						if(map.get("pro_detail_id") != null)
							pro_detail_id =  map.get("pro_detail_id").toString();
						proDetailMap.put("proDetailId", Integer.valueOf(pro_detail_id));
						String ext="";
						if(map.get("ext") != null){
							ext = map.get("ext").toString();
						}
						proDetailMap.put("proDetailTitle",ext);//促销活动名称
						String ext1="";
						if(map.get("ext1") != null){
							ext1 = map.get("ext1").toString();
						}
						proDetailMap.put("proDetailNote",ext1);//促销活动备注
						String pro_gooods = "";
						if(map.get("pro_goods") != null )
							pro_gooods = map.get("pro_goods").toString();
						proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
						if(orderWhetherMeetWholeActivity(pro_type,proDetailMap,shop)){
							wholeOrderPro.add(proDetailMap);
						}
				    }
				}
			}
		    shop.setPromotions(wholeOrderPro);

            //************************************店铺促销活动结束*********************************************************************
			
		/*	if(product.getDiscountMarketPrice() != null){
				shop.setTotalAmount(new BigDecimal(mount).multiply(product.getDiscountMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
			}else{
				shop.setTotalAmount(new BigDecimal(mount).multiply(product.getMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
			}*/
			List<Products> goodsList = shop.getProducts(); 
			goodsList.add(product);
			shops.add(shop);
			//将该订单信息存再session中			
		    request.getSession().setAttribute("memberId",member.getmId());
		    request.getSession().setAttribute("shops", shops);
		    request.getSession().setAttribute("totalItemnum", mount);
		    request.getSession().setAttribute("totalAmount", totalAmount);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	 //立即购买结算提交过来的商品
	private Products getProducts(String goods_sku_id,Goods goods, Member member,int mount,int stocknum ) {
			Products product = new Products();
			product.setProductId(goods.getId());
			product.setMarketPrice(goods.getMarketPrice());
			product = goodsService.discoutProducts(product, member.getmId());	// 根据会员的代理商等级查询代理等级的商品折扣率			
			product.setGoods_sku_id(goods_sku_id);
			product.setGoods_sku_info(getGoodsSkuValuesBySkuIds(goods_sku_id));
			/*if(Common.isNotEmpty(goods.getPicture()))
				product.setPicture(ConfigBeanAdapter.fileAccessAddress + goods.getPicture()); 		*/
			product.setPicture(goods.getPicture());
			product.setProductStock(stocknum);
			product.setProductName(goods.getName());
			product.setQuantity(mount);
			return product;

		}
	//根据库存ID获取商品库存
	public String getGoodsSkuValuesBySkuIds(String goods_sku_id){
		String goods_sku_values="";
		if(Common.isNotEmpty(goods_sku_id)){
			String[] goods_sku_ids = goods_sku_id.split(",");
			if(goods_sku_ids.length > 0){
				for(String sku_id: goods_sku_ids){
					Map<String,Object> paramMap = new LinkedHashMap<String, Object>();	
					paramMap.put("goods_sku_id", sku_id);
					paramMap = goodsSkuService.selectGoodsSkuById(paramMap);
					if(paramMap != null && paramMap.size() > 0){
						goods_sku_values += paramMap.get("base_sku_name").toString() +":"+ paramMap.get("base_sku_value_name").toString() +",";
					}
				}
			}
		}
		return goods_sku_values;
	}
	//获取商品库存
    public int getProductStockNum(Integer goodsId, String goods_sku_id ){
    	String goods_sku_info="";
    	int stocknum =0;
    	if(Common.isNotEmpty(goods_sku_id)){
    		goods_sku_info = getGoodsSkuValuesBySkuIds(goods_sku_id);
        	String[] skuInfoArrs={};
    		GoodsStock goodsStock = new GoodsStock();
    		if(Common.isNotEmpty(goods_sku_info)){
    			skuInfoArrs =goods_sku_info.split(",");			
    			goodsStock.setGoodsId(goodsId);	
    			stocknum = goodsService.getProductStock(goodsStock,skuInfoArrs);		
    		}
    	}
    	return stocknum;
    }
 
	
	//订单列表订单付款页面
	@RequestMapping(value="/order_card_pay")
	public String order_card_pay(Model model,String orderId,HttpServletRequest request){
		try{
			Order order = orderService.selectOrderByOrderId(orderId);
			List<Products>  products  = orderService.selectOrderProductsByOrderId(orderId);
			model.addAttribute("order", order);
			model.addAttribute("products", products);
			model.addAttribute("order_expired_time", ConfigBeanAdapter.chan_qpay_order_expired_time+"天之内");
			model.addAttribute("detailPay","detailPay");//订单详情页付款操作
		}catch(Exception e){
			e.printStackTrace();
		}
		return "/order/pay";
	}
	
	//订单支付成功页面
	@RequestMapping(value="/pay_success")
	public String pay_success(HttpServletRequest request,HttpServletResponse response,Model model){		
		//清除session和cookie中的订单信息,只在model中记录订单号
	    request.getSession().removeAttribute("shops");
	    request.getSession().removeAttribute("totalItemnum");
	    request.getSession().removeAttribute("totalAmount");
		request.getSession().removeAttribute("order_expired_time");
		List<Order> orders = (List<Order> ) request.getSession().getAttribute("orders");
		request.getSession().removeAttribute("orders");
		model.addAttribute("orders", orders);
		return "/order/pay_success";
	}
	//订单列表页面
	@RequestMapping(value="/orderPage")
	public String orderPage(HttpServletRequest request,Model model){
		String queryStatus=request.getParameter("queryStatus");
		model.addAttribute("queryStatus", queryStatus);
		return "/order/all_order";
	}
	//订单结算页面
	@RequestMapping(value="/confirm_order")
	public String confirm_order(Model model, HttpServletRequest requet){
	    return "/order/confirm_order";
	}
	//订单支付页面
	@RequestMapping(value="pay")
	public String card_pay(Model model,HttpServletRequest request){
	//	List<Shop> shops = (ArrayList<Shop>)request.getSession().getAttribute("shops");
		return "/order/pay";
	}
	/**
	 * @Title: oneOrder
	 * @Description 根据订单ID查询订单中订单详情
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value = "oneOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> oneOrder(String orderId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
            OrderDetailDto dto = orderService.selectOrderDetailByOrderId(orderId);
            
			List<Products> list = dto.getProducts();
			if(list != null && list.size() >0){
				for(Products product:list){
					String orderIdExt = product.getOrderId();
					Integer goodsId = product.getProductId();
					List<String> countList = consultCommentService.findIsComment(orderIdExt,goodsId);
					if(countList!=null && countList.size()>0 ){
						product.setIsCommentCount(countList.get(0));
					}else{
						product.setIsCommentCount("0");
					}
					//根据会员的代理商等级查询代理等级的商品折扣率
					//product = goodsService.discoutProducts(product, dto.getMemberId());
					String imgUrl = product.getImgUrl();
					String imgUrl_new = "";
					if(Common.isNotEmpty(imgUrl)){
						String[] urls = imgUrl.split(",");
						for(String url:urls){
							imgUrl_new += ConfigBeanAdapter.fileAccessAddress + url +",";
						}
						product.setImgUrl(imgUrl_new);
					}
					product.setPicture(ConfigBeanAdapter.fileAccessAddress + product.getPicture());
					product = getProProduct(dto,product);
				}
			}
			dto = getProOrderDetail(dto); //获取订单促销活动
			resultMap.put("data", dto);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	//获取订单促销方案
	public OrderDetailDto getProOrderDetail( OrderDetailDto dto){
		try{
			if(Common.isNotEmpty(dto.getProType()) && dto.getProType().equals(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_B)){
	        	String pro_detail_id = dto.getProDetailId();
	        	if(Common.isNotEmpty(pro_detail_id)){
	        		String[] proDetailIds = pro_detail_id.split(",");
	        		for(String proDetailId :proDetailIds){
	        			if(Common.isEmpty(proDetailId)){
	        				continue;
	        			}
		        		PromotionDetailDto proDetailDto =promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailId));
	                    Date now_time = new Date(); //现在时间
					    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
					    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
					    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
							Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
							//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
							proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
							proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
							proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
							String pro_type = proDetailDto.getPro_type();
							String pro_money = proDetailDto.getPro_money();
							String pro_count = proDetailDto.getPro_count();
							String pro_rate = proDetailDto.getPro_rate();	
							String pro_gooods = proDetailDto.getPro_goods();
							proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
							proDetailMap.put("proType", pro_type);//促销类型
							proDetailMap =proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
							dto.setProDetailMap(proDetailMap);
					    }
	        		}
    			}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return dto;
	}
	//获取商品的促销方案
	public Products getProProduct( OrderDetailDto dto ,Products product){
		//计算商品的促销活动
		if(Common.isNotEmpty(dto.getProType()) && dto.getProType().equals(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_A)){ //部分商品促销
        	String pro_goods = dto.getProGoods();
        	String pro_detail_id = dto.getProDetailId();
        	if(Common.isNotEmpty(pro_goods) && Common.isNotEmpty(pro_detail_id)){
        		String[] proGoods = pro_goods.split(",");
        		String[] proDetailIds = pro_detail_id.split(",");
        		for(int i = 0; i< proGoods.length;i++ ){
        			String goodsId = proGoods[i];
        			if(Common.isNotEmpty(goodsId)){
                        String proDetailId = proDetailIds[i];
            			PromotionDetailDto proDetailDto =promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailId));
                        Date now_time = new Date(); //现在时间
    				    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
    				    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
    				    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
    						Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
    						//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
    						proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
    						proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
    						proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
    						String pro_type = proDetailDto.getPro_type();
    						String pro_money = proDetailDto.getPro_money();
    						String pro_count = proDetailDto.getPro_count();
    						String pro_rate = proDetailDto.getPro_rate();								

    						String pro_gooods = proDetailDto.getPro_goods();
    						proDetailMap.put("productId", product.getProductId());
    						proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
    						proDetailMap.put("proType", pro_type);//促销类型
    						proDetailMap =proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
    						product.setGoodsProMap(proDetailMap);
    				    }
        			}
				
        		}
        	}
        }
		return product;
	}
	/**
	 * @Title: cancelOrDeleteOrder
	 * @Description 取消/删除订单 
	 * @param orderId
	 * @param status 0:取消订单 ;1：删除订单
	 * @date 2017年3月13日上午11:50:15
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="cancelOrDeleteOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> cancelOrDeleteOrder(String orderId,String status){		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			if(Common.isEmpty(orderId) || Common.isEmpty(status)){				
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			Order order = new Order();
			order.setOrderId(orderId);
			if(Constants.OrderDetail.STATUSA.equals(status)){
				order.setIsValid(Constants.OrderDetail.OrderStatus.IS_VALIDB);
				
				/*final String orderId_ = orderId;
				new Thread(new Runnable() {

					@Override
					public void run() {
						//恢复商品对应规格的库存
						List<OrderDetail> orderDetailList = orderService.selectOrderDetailList(orderId_);
						if(orderDetailList != null && orderDetailList.size() > 0){
							for(OrderDetail detail :orderDetailList){
								GoodsStock stock = new GoodsStock();
								stock.setGoodsId(detail.getProductId());
								String goods_sku_values = detail.getGoods_sku_info();
								if(Common.isNotEmpty(goods_sku_values)){
									stock = goodsService.getGoodsStock(stock, goods_sku_values.split(","));
								}
								stock.setSaleBaseQuantity(Integer.valueOf((detail.getNumber())));
								int updateGoodsStockResult = goodsService.updateGoodsStock(stock);
								if(updateGoodsStockResult  <= 0){
								}
							}
						}
					}
				});
				*/
			}else if(Constants.OrderDetail.STATUSB.equals(status)){
				order.setStatus(Constants.OrderDetail.OrderStatus.ORDER_STATUSB);  
				order.setIsDelete(Constants.OrderDetail.OrderStatus.IS_DELETEB);
			}
			int cancelOrDeleteOrderResult =  orderService.updateOrder(order);
			if(cancelOrDeleteOrderResult > 0){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_UPDATE);
			}
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAIL);
		}
		return resultMap;
	}
	/**
	 * @Title: expressList
	 * @Description 查询快递列表
	 * @date 2017年3月25日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="expressList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> expressList(){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			List<Express> list = orderService.selectByParam();
		   	resultMap.put("data", list);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);		   	
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}		
		return resultMap;
	}
	
	/**
	 * @title 订单结算
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="tallyOrders")
	@ResponseBody
	public JSONObject tallyOrders(HttpServletRequest request,Model model){
		JSONObject json = new JSONObject();
		Map<String,Shop> shopsMap = new LinkedHashMap<String, Shop>();
		List<Shop> shops = new ArrayList<Shop>();
		try{
			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				json.put("sessionValid", true); //会话失效
				return json;
			}
			String ids = getPara("ids");
			if(Common.isEmpty(ids)){
				json.put("flag", false);
				return json; 
			}
			String[] idsArr = ids.split(",");
			if(idsArr == null || idsArr.length == 0 ){
				json.put("flag", false);
				return json; 
			}
		   List<Products> goodsList = null;
		   String stockMessage ="";//提示信息

		    for(int i = 0; i < idsArr.length ; i++){
				Cart cart = cartService.getCartByCartId(idsArr[i]);
				if(cart == null){
					json.put("resubmitFlag", true);
					return json; 
				}
				String sellerId = cart.getSellerId();
				Seller seller = orderService.getSellerById(Integer.valueOf(sellerId));//店铺信息]
				if(seller == null){
					json.put("flag", false);
					return json;
				}
				Goods goods = goodsService.selectByPrimaryKey(cart.getProductId());//商品信息
			    Products product = getProducts(cart,goods,member);		//获取购物车结算提交的数据	    
				List<Map<String,Object>> goodsProMapList = new ArrayList<Map<String, Object>>();
			    Shop shop =null;
				if(shopsMap.isEmpty() || shopsMap.get(sellerId) == null){
					shop = new Shop();
					shop.setSellerId(sellerId);
					shop.setShopName(seller.getSellerName());
					shop.setItemnum(cart.getQuantity());
					if(product.getDiscountMarketPrice() != null){
						BigDecimal $total = Arith.mul(new BigDecimal(cart.getQuantity()), product.getDiscountMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
						shop.setTotalAmount($total);
					}else{
						BigDecimal $total = Arith.mul(new BigDecimal(cart.getQuantity()), product.getMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
						shop.setTotalAmount($total);
					}
					shopsMap.put(cart.getSellerId(), shop);
					goodsList = shop.getProducts();
					goodsList.add(product);					
				}else{
					shop = shopsMap.get(sellerId);
					shop.setItemnum(product.getQuantity() + shop.getItemnum());					
					if(product.getDiscountMarketPrice() != null){
						BigDecimal $total = Arith.mul(new BigDecimal(cart.getQuantity()), product.getDiscountMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
						$total = Arith.add(shop.getTotalAmount(), $total);
						shop.setTotalAmount($total);
					}else{
						BigDecimal $total = Arith.mul(new BigDecimal(cart.getQuantity()), product.getMarketPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
						$total = Arith.add(shop.getTotalAmount(), $total);
						shop.setTotalAmount($total);;
					}
					goodsList = shop.getProducts();
					goodsList.add(product);				
				}
				
				//判断结算的商品是否超库存				
				if(product.getProductStock() == 0){					
					goodsList.remove(product);  //如果商品库存为0 商品失效不再返回该商品
					stockMessage += goods.getName() + ",商品对应规格库存不足,"+"该商品已经失效"+"\n";
					continue;
				}else if(product.getProductStock() < 0 || product.getProductStock() < product.getQuantity()){
					stockMessage += goods.getName() + ",商品库存不足,"+"请修改购物车商品数量"+"\n";
				}			
				//计算促销方式
				//判断部分商品活动集合中是否已有该商品参与促销了
				if(isGoodsIdNotExistInGoodsProMapList(goodsProMapList,product.getProductId())){
					//查询商品参与的促销活动
					List<PromotionGoodsSkuDto>  goodsProList = promotionService.getGoodsProInfo(product.getProductId());
					if(goodsProList != null && goodsProList.size() > 0){
						for(PromotionGoodsSkuDto goodsSkuDto : goodsProList){						
							List<PromotionDetailDto> goodsProDetailList = promotionService.selectProDetailByProId(goodsSkuDto.getPro_id());
							for(PromotionDetailDto proDetailDto :goodsProDetailList){
	                            Date now_time = new Date(); //现在时间
							    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
							    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
							    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
									Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
									//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
									proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
									proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
									proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
									String pro_type = proDetailDto.getPro_type();
									String pro_money = proDetailDto.getPro_money();
									String pro_count = proDetailDto.getPro_count();
									String pro_rate = proDetailDto.getPro_rate();								

									String pro_gooods = proDetailDto.getPro_goods();
									proDetailMap.put("productId", product.getProductId());
									proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
									proDetailMap.put("proType", pro_type);//促销类型
									proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
									if(goodsWhetherMeetWholeActivity(pro_type,proDetailMap,product)){
										goodsProMapList.add(proDetailMap);
									}
							    }
							}
						}
					}
				}
				product.setGoodsProMapList(goodsProMapList);
		   }
		    shops = getShopArrList(shopsMap); //获取店铺集合
		    
		    int  totalItemnum =0;
		    BigDecimal totalAmount = null;
		    for(Shop shop : shops){
		    	totalItemnum += shop.getItemnum();
		    	if(totalAmount == null){
		    		totalAmount = shop.getTotalAmount();
		    	}else{
		    		totalAmount = Arith.add(shop.getTotalAmount(),totalAmount );
		    	}
			    //计算订单的促销方案
				List<Map<String,Object>> wholeOrderPro = new ArrayList<Map<String, Object>>();
				//查询所有促销活动
				List<Map<String,Object>> proDetailDtoMapList  =  promotionService.selectByParam(null);
				if(proDetailDtoMapList != null && proDetailDtoMapList.size() >0){
					for(Map<String,Object> map :proDetailDtoMapList){
	                    Date now_time = new Date(); //现在时间
					    Date pro_start = DateUtil.dateStrToYMDHMSDate(map.get("pro_start").toString()); //促销开始时间
					    Date pro_end  = DateUtil.dateStrToYMDHMSDate(map.get("pro_end").toString()); //促销结束时间

					    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
							Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
							String pro_type ="";
							if(map.get("pro_type") != null)
						       pro_type = map.get("pro_type").toString();
							proDetailMap.put("proType", pro_type);
							String pro_money ="";
							if(map.get("pro_money") != null)
							   pro_money = map.get("pro_money").toString();
							String pro_count = "";
							if(map.get("pro_count") != null)
							   pro_count = map.get("pro_count").toString();
							String pro_rate = "";
							if(map.get("pro_rate") != null)
							   pro_rate =map.get("pro_rate").toString();
							//String pro_title="";
							//if(map.get("pro_title") != null)
							//	pro_title =  map.get("pro_title").toString();
							//proDetailMap.put("proTitle", pro_title);//促销名称
							String pro_detail_id="";
							if(map.get("pro_detail_id") != null)
								pro_detail_id =  map.get("pro_detail_id").toString();
							proDetailMap.put("proDetailId", Integer.valueOf(pro_detail_id));
							String ext="";
							if(map.get("ext") != null){
								ext = map.get("ext").toString();
							}
							proDetailMap.put("proDetailTitle",ext);//促销活动名称
							String ext1="";
							if(map.get("ext1") != null){
								ext1 = map.get("ext1").toString();
							}
							proDetailMap.put("proDetailNote",ext1);//促销活动备注
							String pro_gooods = "";
							if(map.get("pro_goods") != null )
								pro_gooods = map.get("pro_goods").toString();
							proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
							if(orderWhetherMeetWholeActivity(pro_type,proDetailMap,shop)){
								wholeOrderPro.add(proDetailMap);
							}
					    }
					}
				}
			    shop.setPromotions(wholeOrderPro);

		    }
		    json.put("memberId",member.getmId());
			json.put("shops", shops);
			json.put("stockMessage", stockMessage);
		    request.getSession().setAttribute("memberId",member.getmId());
		    request.getSession().setAttribute("shops", shops);
		    request.getSession().setAttribute("stockMessage", stockMessage);
		    request.getSession().setAttribute("totalItemnum", totalItemnum);
		    request.getSession().setAttribute("totalAmount", totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
			   if(Common.isNotEmpty(stockMessage)){
				   json.put("flag", false);  
			   }else{
				   json.put("flag", true);
			   }
			   json.put("flag", true);
			}catch(Exception e){
				e.printStackTrace();
				json.put("flag", false);
				return json;
			}
			return json;
	}
	
	
	/**
	 * @Title: generateOrders
	 * @Description 提交订单(仿淘宝天猫) 运费系统后台重算一遍，订单总金额要在订单参与促销活动的总金额基础上再累加
	 * @param param
	 * @date 2017年3月13日上午08:49:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="generateOrders")
	@ResponseBody
	@Transactional
	public Map<String,Object> generateOrders(String param ,HttpServletRequest request,HttpServletResponse response){
		OrderBalance balance = null;
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
	    int addOrderResult=0;
	    String exception_desc ="";
		List<Order> orders = new ArrayList<Order>();
	    try{
	    	balance = JSON.parseObject(param, OrderBalance.class);   
			if(param == null || balance == null){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			//ex苏宁易购订单，包含四部分：1.配送信息；2.支付方式；3.商品及服务信息；4.发票信息；5.结算信息
			//创建订单
			//订单编号
			List<Shop> shops = balance.getShops();
			if(shops == null){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			//订单创建日期
			Date createDate = new Date();
			//订单创建人
			String memeberId = balance.getMemberId();
			if(Common.isEmpty(memeberId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}

			BigDecimal orderAmount = new BigDecimal(0) ;
			for(Shop shop : shops){
				shop = orderService.getShop(shop,memeberId); //计算该店铺订单的商品总数量与订单总额
				MakeOrderNum  orderNum=new MakeOrderNum();
				String orderId =orderNum.makeOrderNum();
				//商品
				List<Products> products = shop.getProducts();
				if(products == null){				
	    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
	    			return resultMap;
				}
				Order order  = new Order();
				order.setOrderId(orderId);
				order.setMemberId(memeberId);
				order.setSource(Constants.OrderDetail.OrderSource.ORDER_SOURCEB); // 1：pc平台；2：手机触屏；3：微信商城
				String expressId = shop.getExpressId();
				if(Common.isEmpty(expressId)){
	    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_EXPRESS_ID_IS_NOT_NULL);
	    			return resultMap;
				}
				Express express = orderService.selectByExpressById(Integer.valueOf(expressId));
				if(express != null){ 
					order.setShipMethod(express.getName()+"¥"+express.getFee());
					order.setShipMoney(express.getFee());
					order.setExpressName(express.getName());
				}
				
				//发货地址
				MemberAddress address = this.selectAddressById(balance.getMaId());
				if(address == null){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_MEMBER_ADDRESS_NOT_NULL);
	    			return resultMap;
				}
				//生成订单配送信息
				OrderShip orderShip = new OrderShip(orderId,//订单id
						address.getName(),//收件人名称
						address.getProvince()+address.getCity()+address.getCounty()+address.getStreet(),//收件详细地址
						address.getProvinceCode(),//省级行政区域代码
						address.getProvince(), //省级行政区域名称
						address.getCityCode(),//市级行政区域代码
						address.getCity() ,//市级行政区域名称
						address.getCityCode(),//县级行政区域代码
						address.getCounty() ,//县级行政区域名称
						address.getTel(),//收件人联系电话
						address.getPostcode(),//邮政编码
						"1"//收件人性别
						);

				exception_desc =  ExceptionEnum.DATA_INSERT.getDesc();
				orderService.insert(orderShip);
				
				//发票
				Tax tax = shop.getTax();
				if(tax == null){
					order.setIsTax(Constants.OrderDetail.TaxType.TAX_TYPEA);
				}else{
					order.setScoreU(tax.getScoreU());
					order.setIsTax(tax.getIsTax());
					order.setTaxType(tax.getTaxType());
					order.setCostTax(tax.getCostTax());
					order.setTaxCompany(tax.getTaxCompany());
					order.setTaxContent(tax.getTaxContent());
					order.setInvoiceAmount(tax.getInvoiceAmount());
				}
				
	            //订单信息
				if(Common.isEmpty(shop.getSellerId())){
					order.setSellerId(Constants.SELLERID);		
				}else{	
					order.setSellerId(shop.getSellerId());		
				}
				order.setMemo(shop.getMemo());//订单备注
				order.setWeight(shop.getWeight());				
				order.setCreateDate(createDate);
				order.setCreater(memeberId);
				order.setPayStatus(Constants.OrderDetail.OrderPay.PAY_STATUSC);
				order.setStatus(Constants.OrderDetail.OrderStatus.ORDER_STATUSA);
				order.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTA);//是否评论0：没有评论，1：有评论
				order.setIsValid(Constants.OrderDetail.OrderStatus.IS_VALIDA);//订单是否失效
				order.setIsDelete(Constants.OrderDetail.OrderStatus.IS_DELETEA);//订单是否删除
				order.setPromotionType(Constants.OrderDetail.OrderSales.PROMOTION_TYPEA); //销售类型 1:普通订单;2:预售订单; 
				order.setShipStatus(Constants.OrderDetail.OrderDeliver.SHIP_STATUSA);//发货状态
				order.setModifier(memeberId);
				order.setModifyDate(createDate);
				order.setPayDeadline(DateUtil.getDateAfter(createDate,  Integer.valueOf(ConfigBeanAdapter.chan_qpay_order_expired_time)));//支付截止时间默认7天(真正起作用的是选择完支付方式后会再次修改截止付款时间)
			    order.setIsPmtOrder(Constants.OrderDetail.OrderStatus.IS_PMT_ORDERB);
				//促销活动详情ID
				String proDetailId = shop.getProDetailId();
				PromotionDetailDto proDetailDto = null; //促销活动详情
				if(Common.isNotEmpty(proDetailId)){		
					proDetailDto  = promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailId));	
					if(proDetailDto == null ){						
		    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PROMOTION_DETAIL_IS_NOT_FIND_ERROR);
		    			return resultMap;
					}
	                order.setProType(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_B); //促销方式
					//整单促销
					String pro_type = proDetailDto.getPro_type();
					String pro_money = proDetailDto.getPro_money();
					String pro_count = proDetailDto.getPro_count();
					String gift_pro_goods = proDetailDto.getPro_goods();
					String pro_rate = proDetailDto.getPro_rate();
					switch(pro_type){
						case "0": //订单满减
							if(Common.isNotEmpty(pro_money)){
								order.setPmtOrder(new Double(pro_money.split(":")[1]));
							}
							break;
						case "1": //商品满减
							if(Common.isNotEmpty(pro_count)){
								order.setPmtOrder(new Double(pro_money.split(":")[1]));
							}
							break;
						case "2": //商品满赠
							if(Common.isNotEmpty(pro_count)){
								order.setGiftGoods(gift_pro_goods);
							}
							break;
						case "3":  //商品打折
							if(Common.isNotEmpty(pro_count) && Common.isNotEmpty(pro_rate)){
								BigDecimal rate = new BigDecimal(pro_rate);
								rate = Arith.sub(new BigDecimal(100), rate);
								BigDecimal pmtOrder_ =new BigDecimal(shop.getTotalAmount().multiply(rate).doubleValue()/100).setScale(2,   BigDecimal.ROUND_HALF_UP);
								double $pmtOrder =Arith.add( order.getPmtOrder()==null?0d:order.getPmtGoods(), pmtOrder_.doubleValue()) ;
								order.setPmtOrder($pmtOrder);//计算打折后的订单订单促销优惠金额
							}
							break;
				   }

				   order.setIsPmtOrder(Constants.OrderDetail.OrderStatus.IS_PMT_ORDERA);
				   order.setProDetailId(proDetailId); //店铺促销ID
				}
	            String pro_goods = ""; //记录参与促销活动的商品ID以英文逗号隔开
	            String pro_DetailIds=""; 
	            for(Products product :products){
					//根据会员的代理商等级查询代理等级的商品折扣率
				    product = goodsService.discoutProducts(product, memeberId);
					//促销活动详情ID
					String pro_DetailId = product.getProDetailId();
					if(Common.isNotEmpty(pro_DetailId)){
	    				pro_DetailIds += pro_DetailId+",";
	    				PromotionDetailDto pro_DetailDto = promotionService.selectProDetailByPrimaryKey(Integer.valueOf(pro_DetailId));//促销活动详情
		                order.setProType(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_A); //促销方式
						pro_goods += "" +product.getProductId();
						String pro_type = pro_DetailDto.getPro_type();
						String pro_money = pro_DetailDto.getPro_money();
						String pro_count = pro_DetailDto.getPro_count();
						String gift_pro_goods = pro_DetailDto.getPro_goods();
						String pro_rate = pro_DetailDto.getPro_rate();
						switch(pro_type){
							case "1": //商品满减
								if(Common.isNotEmpty(pro_money)){
									order.setPmtGoods(new Double(pro_money.split(":")[1]));
								}
								break;
							case "2": //商品满赠
								if(Common.isNotEmpty(pro_count)){
									order.setGiftGoods(gift_pro_goods);
								}
								break;
							case "3":  //商品打折
								if(Common.isNotEmpty(pro_count) && Common.isNotEmpty(pro_rate)){
									BigDecimal rate = new BigDecimal(pro_rate);
									rate = Arith.sub(new BigDecimal(100), rate);																
									BigDecimal pmtGoods_ = new BigDecimal(0);
									if(product.getDiscountMarketPrice() != null){
										pmtGoods_ = new BigDecimal(product.getDiscountMarketPrice().multiply(new BigDecimal(product.getQuantity())).multiply(rate).doubleValue()/100).setScale(2,   BigDecimal.ROUND_HALF_UP);
									}else{
										pmtGoods_ = new BigDecimal(product.getMarketPrice().multiply(new BigDecimal(product.getQuantity())).multiply(rate).doubleValue()/100).setScale(2,   BigDecimal.ROUND_HALF_UP);
									}
									double $pmtGoods_ =Arith.add( order.getPmtGoods()==null?0d:order.getPmtGoods(), pmtGoods_.doubleValue()) ;
									order.setPmtGoods($pmtGoods_);//计算打折后的订单订单促销优惠金额
								}
								break;
					   }
					}
	            }
	            if(Common.isNotEmpty(pro_DetailIds))
		            order.setProDetailId(pro_DetailIds);

	            order.setProGoods(pro_goods); //记录参与部分商品活动促销的商品ID
				order.setItemnum(shop.getItemnum());
				if(order.getPmtGoods() != null){
					BigDecimal $totalAmount = Arith.sub(shop.getTotalAmount(), new BigDecimal(order.getPmtGoods())); //去除优惠金额之后的订单总额
					if(express != null){
						$totalAmount  =(Arith.add($totalAmount , express.getFee())); //计算含运费之后的订单总金额
					}	
					order.setTotalAmount($totalAmount);
				}else if(order.getPmtOrder() != null ){
					BigDecimal $totalAmount = Arith.sub(shop.getTotalAmount(), new BigDecimal(order.getPmtOrder())); //去除优惠金额之后的订单总额
					if(express != null){
						$totalAmount  =(Arith.add($totalAmount , express.getFee())); //计算含运费之后的订单总金额
					}	
					order.setTotalAmount($totalAmount);
				}else{
					BigDecimal $totalAmount =shop.getTotalAmount();
					if(express != null){
						$totalAmount  =(Arith.add($totalAmount , express.getFee())); //计算含运费之后的订单总金额
					}	
					order.setTotalAmount($totalAmount);
				}
				shop.setTotalAmount(order.getTotalAmount());
            	exception_desc = ExceptionEnum.DATA_ORDER_CREATE_ERROR.getDesc();
	            addOrderResult = orderService.insert(order);
	            if(addOrderResult > 0){
	            	logger.info("订单添加成功");
	            	if(Common.isNotEmpty(pro_DetailIds) || Common.isNotEmpty(proDetailId)){ //添加订单促销活动记录
	                	//记录订单促销活动记录
	                	PromotionOrderRecord record = new PromotionOrderRecord();
	                	record.setCreateTime(createDate);
	                	record.setOrderId(orderId);
	                	if(Common.isNotEmpty(pro_DetailIds)){
	                        record.setProDetailId(pro_DetailIds);                    		
	                	}
	                	if(Common.isNotEmpty(proDetailId)){
	                        record.setProDetailId(proDetailId);
	                	}
	                	promotionService.insertOrderProRecord(record);    
	            	}           	
	            	
	            }
				//生成订单详情
				for(Products product :products){					
					OrderDetail detail = new OrderDetail();
					detail.setOrderId(orderId);
					if(product.getProductId() == null){						
		    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_ID_IS_NOT_NULL);
		    			return resultMap;
					}
					detail.setProductId(product.getProductId());
					detail.setNumber(product.getQuantity());
					Goods good= goodsService.selectOne(product.getProductId());
					product.setMarketPrice(good.getMarketPrice());
					product = goodsService.discoutProducts(product, memeberId);
					if(product.getDiscountMarketPrice() == null){
						detail.setMarketPrice(product.getMarketPrice());
					}else{
						detail.setMarketPrice(product.getDiscountMarketPrice());
					}

					detail.setProductName(good.getName());
					detail.setIsComment(Constants.OrderDetail.OrderStatus.IS_VALIDA);//是否评论0：没有评论，1：有评论
					detail.setScore(product.getScore());  //赠送积分
					if(Common.isNotEmpty(product.getGoods_sku_id())){
						detail.setGoods_sku_id(product.getGoods_sku_id());; //商品规格ID
						String[] goods_sku_ids = product.getGoods_sku_id().split(",");
						String goods_sku_values="";
						if(goods_sku_ids.length > 0){
							for(String sku_id: goods_sku_ids){
								Map<String,Object> paramMap = new LinkedHashMap<String, Object>();	
								paramMap.put("goods_sku_id", sku_id);
								paramMap = goodsSkuService.selectGoodsSkuById(paramMap);
								if(paramMap != null && paramMap.size() > 0){
									goods_sku_values += paramMap.get("base_sku_name").toString() +":"+ paramMap.get("base_sku_value_name").toString() +",";
								}
							}
						}
						detail.setGoods_sku_info(goods_sku_values);; //商品规格信息
					
				}
				exception_desc = ExceptionEnum.DATA_ORDER_CREATE_ERROR.getDesc();
			    orderService.insert(detail);
			    if(addOrderResult >0){
			    	//清除去购物车商品
			    	Cart cart = new Cart();
			    	cart.setProductId(product.getProductId());
			    	cart.setGoods_sku_id(product.getGoods_sku_id());
			    	cart.setMemberId(balance.getMemberId());
			    	List<Cart> cl =cartService.selectByCartInfo(cart);
			    	if(cl != null && cl.size() >0){
			    		Cart c = cl.get(0);
			    		c.setIsDelete(Constants.IS_DELETEB);
			    		int resultDeleteProductResult = cartService.deleteProduct(c);
			    		if(resultDeleteProductResult >0 ){
			    			cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
							logger.info("删除购物车商品成功！");
			    		}
			    	}
			    }
			}
				//生成订单支付信息
			    OrderPayment payment = new OrderPayment();
			    payment.setPaymentId(Common.getUUID());
			    payment.setCreateDate(createDate);
			    payment.setCreater(memeberId);
			    payment.setCurMoney(shop.getTotalAmount());  //客户支付货币金额
			    payment.setIsValid(Constants.IS_VALIDA);    //是否有效（1：有效；0：无效）
			    payment.setMoney(shop.getTotalAmount());//支付金额
			    payment.setMemberId(memeberId);
			    payment.setModifier(memeberId);
			    payment.setModifyDate(createDate);
			    payment.setOrderId(orderId);
			    payment.setSellerId(Constants.SELLERID);			    
			    payment.setStatus(Constants.OrderDetail.OrderPay.PAY_STATUSC); //支付状态1:支付成功,2:支付失败;3:未支付;4:处理异常;5:非法参数;\r\n 6:已付款至担保方;7:超时;8:准备中; 
			    payment.setType(Constants.OrderDetail.OrderPay.PayType.TYPEB); //类型（0：退款，1：付款）
				exception_desc = ExceptionEnum.DATA_ORDER_PAYMENT_CREATE_ERROR.getDesc();

			    orderAmount =Arith.add(orderAmount, order.getTotalAmount()); 	
			    orderService.insert(payment);		
				orders.add(order);
			}
			
			resultMap.put("data",orders);
			//清除session中关于订单结算的信息
		    request.getSession().removeAttribute("stockMessage");
		    request.getSession().removeAttribute("promotions");
			//将成功提交的订单信息记录的session中
			request.getSession().setAttribute("orderBalance", balance);
			request.getSession().setAttribute("orders", orders);
			request.getSession().setAttribute("totalAmount", orderAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
			request.getSession().setAttribute("order_expired_time", ConfigBeanAdapter.chan_qpay_order_expired_time+"天之内");
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_CREATE_SUCCESS);
	    }catch(Exception e){
			e.printStackTrace();
	    	throw new RuntimeException( exception_desc);
	    }
		return resultMap;
	}
	/**
	 * @Title payDetail
	 * @Description  通过订单ID获取订单支付结果
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="payDetail",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> payDetail(String orderId){
		Map<String,Object> resultMap=new LinkedHashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_ID_IS_NULL);
				return resultMap;
			}

			if(Common.isEmpty(orderId) ){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_FIND_ERROR);
				return resultMap;
			}
			List<OrderPayment> list =new ArrayList<OrderPayment>();
			OrderPayment payment =new OrderPayment();
			payment.setOrderId(orderId);
			
			list =orderService.selectByPayments(payment);
	    	
	    	//2017年4月5日修改,由于当前系统只支持单店铺，不存在提交一个订单，生成多个支付详单的情况，默认一个订单生成一个支付详单
			payment = list.get(0);
			if(payment.getStatus().equals(Constants.OrderDetail.OrderPay.PAY_STATUSC)){	
				resultMap.put("status", Constants.OrderDetail.OrderPay.PAY_STATUSC);			
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_NOTPAY);
			}else{
				if(payment.getStatus().equals(Constants.OrderDetail.OrderPay.PAY_STATUSF)){
					resultMap.put("status", Constants.OrderDetail.OrderPay.PAY_STATUSF);
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_MONEY_TO_BANK);
				}else if(payment.getStatus().equals(Constants.OrderDetail.OrderPay.PAY_STATUSA)){
					resultMap.put("status", Constants.OrderDetail.OrderPay.PAY_STATUSA);
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_SUCCESS);
				}
			}			
			resultMap.put("orderId", payment.getOrderId());
			resultMap.put("transactionId", payment.getTransactionId());
			resultMap.put("paymentBank", payment.getPaymentBank());
			resultMap.put("paymentAccount", payment.getPaymentAccount());
			resultMap.put("money", payment.getMoney());
			resultMap.put("payer", payment.getPayer());
			resultMap.put("payType", payment.getPayType());
			resultMap.put("curMoney", payment.getCurMoney());
			resultMap.put("payCreate", payment.getPayCreate());
			resultMap.put("payClose", payment.getPayClose());
			resultMap.put("payTime", payment.getPayTime());
			resultMap.put("type", payment.getType());
			resultMap.put("payName", payment.getPayName());
			
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	/**
	 * 获取用户的发货地址
	 * @param maId
	 * @return
	 */
	private MemberAddress selectAddressById(String maId) {
		return memberAddressService.selectAddressById(maId);
	}

    /**
     * @title 从Map集合获取店铺集合
     * @param shops
     * @return
     */
	private List<Shop> getShopArrList(Map<String, Shop> shopMap) {
		List<Shop> shops = new ArrayList<Shop>();
		for (String key : shopMap.keySet()) {  
		   System.out.println("key= "+ key + " and value= " + shopMap.get(key));  
		   shops.add(shopMap.get(key));
		}  
		return shops;
	}
	//判断部分商品活动集合中是否已有该商品参与促销了
	public boolean isGoodsIdNotExistInGoodsProMapList (List <Map<String,Object>> goodsProMapList ,Integer productId){
		if(goodsProMapList == null || goodsProMapList.size() ==0){
			return true;
		}
		for(Map<String,Object> map :goodsProMapList){
			if(map.get("productId").toString().equals(productId+"")){
				return false;
			}
		}
		return true;
	}
	//判断商品列表是否存在同一商品不同规格的商品
	public boolean isExistTheSameSpecificationGoods(Products product ,List<Products> products){
		for(Products p: products){
			if(product.getProductId() == p.getProductId()){
				if(!product.getGoods_sku_id().equals(p.getGoods_sku_id())){
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * @title 判断订单中的商品是否满足部分活动 
	 * @param pro_type
	 * @param proDetailMap
	 * @param product
	 * @return
	 */
	public boolean goodsWhetherMeetWholeActivity(String pro_type, Map<String, Object> proDetailMap, Products product){
		boolean flag = false;
		int  itemnum =product.getQuantity(); //商品数量
        BigDecimal totalAmount =  new BigDecimal(0);
        if(product.getDiscountMarketPrice() != null){
        	totalAmount =  product.getDiscountMarketPrice().multiply(new BigDecimal(itemnum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }else {
        	totalAmount =  product.getMarketPrice().multiply(new BigDecimal(itemnum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        switch(pro_type){
			case "0": //订单满减
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if(itemnum >=Integer.valueOf(proDetailMap.get("mustQuantity").toString())){
						flag = true;
					}
				}
				break;
			case "1": //商品满减
				if(proDetailMap.get("mustQuantity") != null){
				//	System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( totalAmount.compareTo(new BigDecimal(proDetailMap.get("mustQuantity").toString())) >=0 ){
						flag = true;
					}
				}
				break;
			case "2": //商品满赠
				if(proDetailMap.get("mustQuantity") != null){
				//	System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
			case "3":  //商品打折
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
	        }
		return flag;
	}
	/**
	 * 封装促销活动返回集合
	 * @param proDetailMap
	 * @param pro_type
	 * @param pro_money
	 * @param pro_count
	 * @param pro_rate
	 * @param pro_gooods
	 * @return
	 */
	public Map<String ,Object> proDetailMap(Map<String ,Object> proDetailMap,String pro_type,String pro_money,String pro_count,String pro_rate,String pro_gooods){
		 List<Goods> goodsList =new ArrayList<Goods>();//满赠商品列表  
			String[] goods_ids =null;
			if(Common.isNotEmpty(pro_gooods)){
				goods_ids =pro_gooods.split(",");
				for(String goods_id : goods_ids){
					Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(goods_id));
					goodsList.add(goods);
				}
			}
		switch(pro_type){
			case "0": //订单满减
				if(Common.isNotEmpty(pro_money)){
					proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
					proDetailMap.put("discountAmount", pro_money.split(":")[1]);
				}
				break;
			case "1": //商品满减
				if(Common.isNotEmpty(pro_money)){
					proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
					proDetailMap.put("discountAmount", pro_money.split(":")[1]);
				}
				break;
			case "2": //商品满赠
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity", pro_count.split(":")[0]);
					proDetailMap.put("giveNumber", pro_count.split(":")[1]);
					proDetailMap.put("giveList", goodsList);
				}
				break;
			case "3":  //商品打折
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity", pro_count);//商品满足数量
					BigDecimal rate = new BigDecimal(new Double(pro_rate)/100).setScale(2, BigDecimal.ROUND_HALF_UP);
					proDetailMap.put("discountRate",rate.toString());//商品打折率
				}
				break;
		}
		return proDetailMap;
	}

    //获取购物车结算提交过来的商品
	private Products getProducts(Cart cart,Goods goods, Member member) {
		Products product = new Products();
		product.setProductId(goods.getId());
		product.setMarketPrice(goods.getMarketPrice());
		// 根据会员的代理商等级查询代理等级的商品折扣率
		product = goodsService.discoutProducts(product, member.getmId());
		product.setGoods_sku_id(cart.getGoods_sku_id());
		product.setGoods_sku_info(cart.getGoods_sku_info());
		if(Common.isNotEmpty(goods.getPicture()))
			product.setPicture(ConfigBeanAdapter.fileAccessAddress + goods.getPicture()); 
		String[] skuInfoArrs={};
		GoodsStock goodsStock = new GoodsStock();
		if(Common.isNotEmpty(cart.getGoods_sku_info())){
			skuInfoArrs = cart.getGoods_sku_info().split(",");			
			goodsStock.setGoodsId(goods.getId());			
		}
		int stocknum = goodsService.getProductStock(goodsStock,skuInfoArrs);
		product.setProductStock(stocknum);
		if(stocknum <= 0 || stocknum < cart.getQuantity()){
			product.setProductDetail(goods.getName() + "商品库存不足"+"请修改购物车商品数量");
		}else{
			product.setProductDetail(goods.getName() + "商品库存充足");
		}
		product.setProductName(goods.getName());
		product.setQuantity(cart.getQuantity());
		return product;

	}
	

	/**
	 * @title 判断订单是否满足整单活动 
	 * @param proDetailMap
	 * @param shop
	 * @return flag true可以参与活动,false不能参与活动
	 */
	public boolean orderWhetherMeetWholeActivity(String pro_type,Map<String ,Object> proDetailMap ,Shop shop){
		boolean flag= false;
		BigDecimal totalAmount = shop.getTotalAmount(); //订单总金额
		int itemnum = shop.getItemnum(); //订单商品数量
	/*	int $itemnum = 0;
		BigDecimal $totalAmount =new BigDecimal(0);
		List<Products> products = shop.getProducts();
		for(Products product:products){
			$itemnum += product.getQuantity();
			if(product.getDiscountMarketPrice() != null){
                BigDecimal $total = Arith.mul(product.getDiscountMarketPrice(), new BigDecimal(product.getQuantity()));
                $totalAmount = Arith.add($totalAmount,$total).setScale(2, BigDecimal.ROUND_HALF_UP);
			}else{
                BigDecimal $total = Arith.mul(product.getMarketPrice(), new BigDecimal(product.getQuantity()));
                $totalAmount = Arith.add($totalAmount,$total).setScale(2, BigDecimal.ROUND_HALF_UP);;
			}
		}
		if(itemnum != $itemnum){
			itemnum = $itemnum;
		}
		if($totalAmount != totalAmount){
			totalAmount =$totalAmount;
		}*/
		switch(pro_type){
			case "0": //订单满减
				if(proDetailMap.get("mustQuantity") != null){
				//	System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if(itemnum >=Integer.valueOf(proDetailMap.get("mustQuantity").toString())){
						flag = true;
					}
				}
				break;
			case "1": //商品满减
				if(proDetailMap.get("mustQuantity") != null){
				//	System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( totalAmount.compareTo(new BigDecimal(proDetailMap.get("mustQuantity").toString())) >=0 ){
						flag = true;
					}
				}
				break;
			case "2": //商品满赠
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
			case "3":  //商品打折
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
	}
		
		return flag;
	}
	/**
	 * @Title: orderList
	 * @Description 查询订单列表
	 * @param queryStatus 查询状态 0：全部,1：待付款,2:待发货，3:待收货，4：待评价 ，5：退换货
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="orderList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> orderList(Integer currPage,Integer pageSize,String memberId,String queryStatus , String commentStatus,String orderStatus, String likeStr,HttpServletRequest request){		
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		Page page = new Page();
		// 传入页号
		page.setCurrPage(currPage);
		// 传入每页记录数
		page.setPageSize(pageSize);
		
		Orders order = new Orders();
		// 添加查询条件
		order.setMemberId(memberId);
		
		order.setQueryStatus(queryStatus);
		order.setCommentStatus(commentStatus);
		order.setOrderStatus(orderStatus);
		List<Orders> resultList = new ArrayList<Orders>();
		int totalRecords = 0;
		int totalPage = 0;
		try {
			/*if(currPage == null || pageSize == null || Common.isEmpty(memberId) || Common.isEmpty(queryStatus)){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
		    }*/
			PaginationBean<Orders> result = orderService.getPagingDatas(order,
					page, "count", "selectByParam",OrderMapper.class);
			resultList = result.getPageList();
			for(Orders o:resultList){
				List<Products> porducts = o.getProducts();
				if(porducts!= null && porducts.size() >0){
					for(Products pro:porducts){
						String orderId = pro.getOrderId();
						Integer goodsId = pro.getProductId();
						List<String> countList = consultCommentService.findIsComment(orderId,goodsId);
						if(countList!=null && countList.size()>0 ){
							pro.setIsCommentCount(countList.get(0));
						}else{
							pro.setIsCommentCount("0");
						}
						//根据会员的代理商等级查询代理等级的商品折扣率
						//pro = goodsService.discoutProducts(pro, memberId);
						if(Common.isNotEmpty(pro.getPicture()))
						   pro.setPicture(ConfigBeanAdapter.fileAccessAddress+pro.getPicture());
					}
				}
			}
			totalRecords = result.getTotalRecords();
			totalPage = result.getTotalPage();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("分页查订单商品异常！");
		
		}
		resultMap.put("count", totalRecords);
		resultMap.put("pages", totalPage);
		resultMap.put("data", resultList);
		return resultMap;
	}
	/**
	 * @Title: confirmReceiptOrder
	 * @Description 确认收货
	 * @param queryStatus 查询状态 0：全部,1：待付款,2:待发货，3:待收货，4：待评价 ，5：退换货
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value = "confirmReceiptOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> confirmReceiptOrder(HttpServletRequest request,String orderId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId) ){				
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				resultMap.put("sessionValid", true); //会话失效
    			return resultMap;
			}
			Order order = new Order();
			order.setOrderId(orderId);
			order.setShipStatus(Constants.OrderDetail.OrderDeliver.SHIP_STATUSF);
			order.setIsDelete(Constants.IS_DELETEA);
			int confirmReceiptOrderResult =  orderService.updateOrder(order);
			if(confirmReceiptOrderResult > 0){

				MemberNews news = new MemberNews(); //交易物流消息
				news.setCreater(member.getmId());
		    	news.setModifier(member.getmId());
				news.setOrderId(orderId);
		    	news.setMemberId(member.getmId());
				news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLEF);
		    	news.setCreateDate(new Date());
		    	news.setModifyDate(new Date()); 
		    	//生成一条消息通知
				orderService.insertMemberNews(news);
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_UPDATE);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
	}
	
	/**
	 * @Title: orderList
	 * @Description 查询订单列表
	 * @param queryStatus 查询状态 0：全部,1：待付款,2:待发货，3:待收货，4：待评价 ，5：退换货
	 * @date 2017年6月8日下午09:50:00
	 * @author xiongyong
	 */
	@RequestMapping(value="/myOrders")
	public ModelAndView myOrders(Integer currPage,Integer pageSize,String memberId,String queryStatus , String commentStatus,String orderStatus, String likeStr,HttpServletRequest request){		
		ModelAndView mav = null;
		if(queryStatus!=null && "5".equals(queryStatus)){
			mav = new ModelAndView("/order/refund");  //退换货
		}else{
			mav = new ModelAndView("/order/my_orders");  //订单类型
		}
		mav.addObject("queryStatus", queryStatus);
		return mav;
	}
	
	
}
